package com.lee.boot.head.first.demo.redis.message;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

/**
 * @author edz
 */
@Component
public class RedisMessageListenerThread {

    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    @Autowired
    MessageListener redisMessageListener;

    @Autowired
    RedisTemplate redisTemplate;


    private ThreadPoolTaskScheduler threadPoolTaskScheduler = null;


    @Bean
    public ThreadPoolTaskScheduler initThreadPoolTaskScheduler() {
        if (threadPoolTaskScheduler != null) {
            return threadPoolTaskScheduler;
        }
        threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.setPoolSize(20);
        return threadPoolTaskScheduler;
    }

    @Bean
    public RedisMessageListenerContainer initRedisContainer() {
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
        ChannelTopic topic1 = new ChannelTopic("topic1");
        redisMessageListenerContainer.addMessageListener(redisMessageListener, topic1);
        redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
        redisMessageListenerContainer.setTaskExecutor(initThreadPoolTaskScheduler());
        return redisMessageListenerContainer;

    }


}
